<template>
  <!-- 周排班方案表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      style="min-width: 600px; max-width: 800px"
      draggable
      @close="closeDialog"
    >
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100">
        <el-row>
          <el-col :span="12">
            <el-form-item label="周班制编号" prop="shiftWeekSetCode">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.shiftWeekSetCode"
                placeholder="请输入周班制编号"
                clearable
              />
              <span v-else>{{ formData.shiftWeekSetCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="周班制名称" prop="shiftWeekSetName">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.shiftWeekSetName"
                placeholder="请输入周班制名称"
                clearable
              />
              <span v-else>{{ formData.shiftWeekSetName }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="工厂" prop="plantId">
              <el-select
                v-if="!props.isReadonly"
                v-model="formData.plantId"
                placeholder="请输入工厂"
                clearable
                style="width: 400px"
                @change="changePlant"
                filterable
              >
                <el-option
                  v-for="plant in plantList"
                  :key="plant.id"
                  :label="plant.organizationCode"
                  :value="plant.id"
                />
              </el-select>
              <span v-else>{{ plantCode(formData.plantId) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否启用" prop="enabled">
              <el-radio-group
                v-model="formData.enabled"
                v-if="!props.isReadonly"
              >
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
              <span v-else>{{ formData.enabled == 1 ? "启用" : "停用" }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-if="!props.isReadonly"
            v-model="formData.remarks"
            placeholder="请输入备注"
            clearable
            show-word-limit
            type="textarea"
            maxlength="255"
          />
          <span v-else>{{ formData.remarks }}</span>
        </el-form-item>
        <el-row v-show="props.isReadonly">
          <el-col :span="12">
            <el-form-item label="创建时间">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.createTime"
                placeholder="请输入创建时间"
                clearable
              />
              <span v-else>{{ formData.createTime }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建人">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.createdUserName"
                placeholder="请输入创建人"
                clearable
              />
              <span v-else>{{ formData.createdUserName }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="props.isReadonly">
          <el-col :span="12">
            <el-form-item label="更新时间">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.lastUpdateTime"
                placeholder="请输入更新时间"
                clearable
              />
              <span v-else>{{ formData.lastUpdateTime }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="更新人">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.lastUpdatedUserName"
                placeholder="请输入更新人"
                clearable
              />
              <span v-else>{{ formData.lastUpdatedUserName }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="班制选择">
          <el-select
            v-if="!props.isReadonly"
            v-model="messhiftSet"
            value-key="id"
            :disabled="formData.plantId === ''"
            placeholder="请选择班制"
            clearable
            @change="selectMesshiftSet"
          >
            <el-option
              v-for="messhift in messhiftSetList"
              :key="messhift.id"
              :label="messhift.shiftSetName"
              :value="messhift"
            />
          </el-select>
          <span v-else>{{ plantCode(formData.plantId) }}</span>
        </el-form-item>
        <el-card shadow="never" class="table-container">
          <div class="formTable">
            <el-table
              :data="formData.details"
              style="width: 100%"
              max-height="300"
              :key="Math.random"
              border
            >
              <el-table-column
                type="index"
                label="序号"
                align="center"
                width="100"
              />
              <el-table-column
                label="星期"
                align="center"
                prop="daySequenceName"
                width="150"
              />
              <el-table-column label="班制" min-width="150">
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.shiftSetId'"
                    :rules="rules.shiftSetId"
                    label-width="0"
                  >
                    <el-select
                      v-if="!props.isReadonly"
                      v-model="row.shiftSetId"
                      style="width: 100%"
                      :disabled="formData.plantId === ''"
                      placeholder="请选择班制"
                      clearable
                      @change="selectMesshiftSetOne"
                    >
                      <el-option
                        v-for="messhift in messhiftSetList"
                        :key="messhift.id"
                        :label="messhift.shiftSetName"
                        :value="messhift.id"
                      />
                    </el-select>
                    <span v-else>{{ messhiftName(row.shiftSetId) }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MESMESSHIFTWEEKSETADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    if (newVal && !props.data.id) {
      getMesshiftWeekList();
    } else {
      getMesshiftSetList();
    }
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  shiftWeekSetCode: "",
  shiftWeekSetName: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
  details: [
    {
      id: "",
      shiftWeekSetId: "",
      daySequenceName: "",
      daySequenceCode: "",
      shiftSetId: "",
      shiftSetCode: "",
      version: "",
      remarks: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
      enabled: "",
      deleted: "",
    },
  ],
});

/** rules规则 */
const rules = reactive({
  shiftWeekSetCode: [
    { required: true, message: "请输入排班方案编号", trigger: "blur" },
  ],
  shiftWeekSetName: [
    { required: true, message: "请输入排班方案名称", trigger: "blur" },
  ],
  plantId: [{ required: true, message: "请输入工厂", trigger: "blur" }],
  enabled: [{ required: true, message: "请输入是否启用", trigger: "blur" }],
  shiftSetId: [{ message: "请选择班制", trigger: "blur" }],
});

/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
};

const details = {
  id: "",
  shiftWeekSetId: "",
  daySequenceName: "",
  daySequenceCode: "",
  shiftSetId: "",
  shiftSetCode: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  formData.details.push(sondata);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        getdetails();
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [details];
  formData.id = "";
  formData.shiftWeekSetCode = "";
  formData.shiftWeekSetName = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
}

const loading = ref(false);

/** 周排班方案保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/mes/messhiftweekset/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

async function getdetails() {
  let sondetails = await request({
    url: "/mes/messhiftweekset/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
}

//工厂列表
const plantList = ref([]);
const getPlantList = async () => {
  const { data } = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = data;
};
// 回显Code
const plantCode = (id: string) => {
  if (id) {
    const data = plantList.value.find((item) => item.id === id);
    return data.organizationCode;
  }
};
// 工厂Code
const changePlant = (id: any) => {
  if (id) {
    formData.plantId = id;
    formData.plantCode = plantCode(id);
    messhiftSetList.value = [];
    messhiftSet.value = {};
    formData.details.forEach((item: any) => {
      item.shiftSetId = "";
      item.shiftSetCode = "";
    });
    getMesshiftSetList();
  }
};

//班制id
const messhiftSet = ref({});
//班制列表
const messhiftSetList = ref([]);
//获取班制列表
const getMesshiftSetList = async () => {
  const { data } = await request({
    url: "mes/messhiftset/getList",
    method: "post",
    data: {
      plantId: formData.plantId,
      enabled: 1,
    },
  });
  messhiftSetList.value = data;
  console.log(data);
};
// 批量选择班制
const selectMesshiftSet = (value: any) => {
  formData.details.forEach((item: any) => {
    item.shiftSetId = value.id;
    item.shiftSetCode = value.shiftSetCode;
  });
  console.log(formData.details);
};
// 单选择班制
const selectMesshiftSetOne = (value: string) => {
  let messhiftSet = messhiftSetList.value.find(
    (item: any) => item.id === value
  ) as any;
  let shiftSet = formData.details.find(
    (item: any) => item.shiftSetId === value
  );
  shiftSet!.shiftSetCode = messhiftSet.shiftSetCode;
  console.log(value, formData.details);
};

// 回显Code
const messhiftName = (id: string) => {
  if (id) {
    const data = messhiftSetList.value.find((item) => item.id === id);
    return data.shiftSetName;
  }
};

//获取班制列表
const getMesshiftWeekList = async () => {
  const { data } = await request({
    url: "mes/messhiftweekset/week",
  });
  formData.details = data;
  console.log(data);
};

onMounted(async () => {
  await Promise.all([getPlantList()]);
});
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}

.formTable {
  :deep(.el-form-item) {
    margin-right: 0 !important;
  }
}

:deep(.search-container .el-input.el-input--default.el-input--suffix) {
  // 固定宽度
  width: 190px !important;
}

:deep(.search-container .el-form-item--default .el-form-item__label) {
  // 固定宽度
  justify-content: end;
}

:deep(.el-form-item) {
  margin: 0;
  padding: 13px 0;
}
</style>
